
///
/// shopping_cart_demo02.dart
///

class Meta {
  double price;
  String name;
  Meta(this.name, this.price);
}

class Item extends Meta {
  Item(name, price) : super(name, price);
  Item operator + (Item other) => Item('$name, ${other.name}', price + other.price);
}

abstract class PrintHelper {
  String getInfo();
  printInfo() => print(getInfo());
}

class ShoppingCart extends Meta with PrintHelper {
  DateTime date;
  String? code;
  List<Item>? bookings;

  @override
  double get price => allGoods.price;

  String get goodsName => allGoods.name;

  Item get allGoods {
    /// https://dart.cn/codelabs/null-safety
    /// 按照上面文档的说法，要慎用 `!.` 操作符
    /// If you’re wrong, Dart throws an exception at run-time.
    /// This makes the ! operator unsafe,
    /// so don’t use it unless you’re very sure that the expression isn’t null.
    if (bookings != null) {
      return bookings!.reduce((value, element) => value + element);
    } else {
      return Item('', 0.0);
    }
  }

  ShoppingCart.withCode({name, this.code}) : date = DateTime.now(), super(name, 0);
  ShoppingCart({name}) : this.withCode(name:name, code: null);

  @override
  String getInfo() => '''
购物车信息:
-----------------------------
  用户名: $name
  优惠码: ${code??"没有"}
  商品: $goodsName
  总价: $price
  Date: $date
-----------------------------
''';
}

void main() {
  ShoppingCart.withCode(name: '战三', code: '123456')
    ..bookings = [Item('苹果', 10.0), Item('鸭梨', 20.0)]
    ..printInfo();
  ShoppingCart(name: '李四')
    ..bookings = [Item('香蕉', 15.0), Item('西瓜', 40.0)]
    ..printInfo();
  ShoppingCart(name: '赵柳').printInfo();
}
